package com.itelite.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itelite.common.util.FileUtils;
import com.itelite.common.util.ImageUtils;
import com.itelite.common.util.SecurityUtils;
import com.itelite.config.WebAppConfig;
import com.itelite.domain.dto.*;
import com.itelite.domain.pojo.Group;
import com.itelite.domain.pojo.TrainingRecord;
import com.itelite.domain.pojo.TrainingRecordFile;
import com.itelite.mapper.ConfigMapper;
import com.itelite.mapper.RecordMapper;
import com.itelite.service.GroupService;
import com.itelite.service.RecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/8/6-8:56
 **/
@Service
@Slf4j
public class RecordServiceImpl implements RecordService {
    @Autowired
    private RecordMapper recordMapper;

    @Autowired
    private GroupService groupService;
    @Autowired
    private ConfigMapper configMapper;
    @Transactional
    @Override
    public boolean uploadTrainingRecord(TrainingRecord record, MultipartFile[] files) {
        //验证资格
//        Group root = groupService.getGroupRoot(groupService.queryGroupIdByUserId(SecurityUtils.getUserId()));
//        if (!checkAuthority(root,record.getGroupId())) {
//            log.info("没有上传记录资格");
//            return false;
//        }
        record.setUploadUserId(SecurityUtils.getUserId());
        record.setCoverImage(File.separator+WebAppConfig.ROOT_DIR_COVER+File.separator+record.getGroupId()+".jpg");
        int row = recordMapper.insertTrainingRecord(record);
        if(row<=0) return false;
        // 培训老师
        if(!StringUtils.isEmpty(record.getTeacher())){
            String[] teachers = record.getTeacher().split(",");
            recordMapper.insertRecordTeacher(record.getRecordId(),teachers);
        }
        // 上传培训图片
        if(files!=null){
            List<TrainingRecordFile> fileList = null;
            try {
                fileList = addRecordImage(record.getRecordId(),files);
            } catch (IOException e) {
                log.error("缩略图生成错误");
            }
            if(!CollectionUtils.isEmpty(fileList)){
                //第一张默认生成缩略图
                fileList.get(0).setState(1);
                row = recordMapper.insertRecordFiles(fileList);
                if(row>0){
                    //将缩略图的url拼接后存入record中作为封面
                    String url = fileList.get(0).getFileUrl();
                    url = url.replace(".", "-thumbnail.");
//                    url = url.substring(0, url.lastIndexOf('.'))+"-thumbnail"+fileList.get(0).getExtensionName();
                    recordMapper.updateRecordCover(record.getRecordId(),url);
                }
            }
        }
        return true;
    }

    @Override
    public TrainingRecordDto getTrainingRecordDetail(Integer recordId) {
        return recordMapper.queryTrainingRecordDetail(recordId);
    }

    @Override
    public PageInfo<TrainingRecordVo> getTrainingRecordList(RecordParam param) {
        Integer groupId = param.getGroupId();
        Integer[] groupIds = groupService.getGroupIds(groupId);
        if(ArrayUtils.isEmpty(groupIds))return null;
        param.setGroups(groupIds);
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<TrainingRecordVo> recordList = recordMapper.queryTrainingRecordVo(param);
        return new PageInfo<>(recordList);
    }

    @Override
    public PageInfo<TimelineRecord> getTimelineRecord(BaseParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<TimelineRecord> recordList = recordMapper.queryTimelineRecord();
        return new PageInfo<>(recordList);
    }
//    @Transactional
    @Override
    public boolean deleteRecord(Integer recordId) {
        //检查是否具有删除权限

        Integer userId =  SecurityUtils.getUserId();
        int groupId = groupService.queryGroupIdByUserId(userId);
        Integer[] groupIds = groupService.getGroupIds(groupId);
        int deleteDate = configMapper.queryRecordDeleteDate();
        if (recordMapper.deleteRecord(recordId,deleteDate,userId,groupIds)>0) {
            //删除老师
            recordMapper.deleteRecordTeacher(recordId);
            //删除文件
            List<String> filePaths = recordMapper.queryRecordFilesByRecordId(recordId);
            log.info("需要删除的图片路径"+filePaths);
            recordMapper.deleteRecordFile(recordId);
            //缩略图路径
            if(!CollectionUtils.isEmpty(filePaths)){
                log.info("删除缩略图");
                String url = filePaths.get(0);
                url = url.replace(".", "-thumbnail.");
                log.info("缩略图路径"+url);
                filePaths.add(url);
            }
            for (String path : filePaths) {
                String finalPath = WebAppConfig.ROOT+path;
                File file = new File(finalPath);
                if (file.exists()) {
                    log.info(finalPath+"文件存在");
                    if (file.delete()) {
                        log.info(finalPath+"删除成功");
                    }else {
                        log.info(finalPath+"删除失败");
                    }
                }else {
                    log.info("删除失败"+path);
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public Map<String, Object> getWordRecordParam(Integer recordId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TrainingRecordDto trainingRecord = recordMapper.queryTrainingRecordDetail(recordId);
        if(trainingRecord==null) return null;
        HashMap<String,Object> param = new HashMap<>();
        param.put("groupName",trainingRecord.getGroupName());
        param.put("lecturer",trainingRecord.getLecturer());
        param.put("teachers",trainingRecord.getTeacher());
        param.put("subject",trainingRecord.getSubject());
        param.put("trainingDate",sdf.format(trainingRecord.getTrainingDate()));
        param.put("duration",trainingRecord.getDuration());
        param.put("students",trainingRecord.getStudents());
        param.put("trainingLocation",trainingRecord.getTrainingLocation());
        param.put("detail",trainingRecord.getDetail());
        param.put("imageUrls",trainingRecord.getImages());
        param.put("uploadUser",trainingRecord.getUserVo().getRealName());
        param.put("createDate",sdf.format(trainingRecord.getCreateDate()));
        param.put("size",trainingRecord.getImages().size());
        return param;
    }


    @Override
    public List<TeacherRecordExcel> getTeacherTrainingRecord(RecordParam param) {
//        param.setGroups(groupService.getGroupIds(param.getGroupId()));
        List<TeacherRecordExcel> total = new ArrayList<>();
        List<Integer> teacherIds = recordMapper.queryTeacherForTrainingRecord(param);
        teacherIds.forEach(t->{
            param.setTeacherId(t);
            List<TeacherRecordExcel> list = recordMapper.queryTeacherTrainingRecord(param);
            AtomicInteger s = new AtomicInteger(0);
            for (TeacherRecordExcel excel : list) {
                s.compareAndSet(s.get(),s.get()+excel.getDuration());
                excel.setTotalDuration(s);
            }
            total.addAll(list);
        });
        return total;
    }

    @Override
    public List<GroupRecordExcel> getExcelRecordParam(RecordParam param) {
        Integer[] groupIds = groupService.getGroupIds(param.getGroupId());
        param.setGroups(groupIds);
        List<GroupRecordExcel> list = recordMapper.queryTrainingRecordByGroup(param);
        list.forEach(s->{
            if(s.getTeacher()==null){
                s.setTeacher("无");
            }
        });
        return list;
    }

    @Override
    public Integer getRecordBelongingGroupId(Integer recordId) {
        return recordMapper.queryGroupIdByRecordId(recordId);
    }


    private boolean checkAuthority(Group root,int groupId){
        if(root==null) return false;
        if(root.getGroupId()==groupId) return true;
        else {
            for (Group child : root.getChildren()) {
                if (checkAuthority(child,groupId)) {
                    return true;
                }
            }
        }
        return false;
    }

    private List<TrainingRecordFile> addRecordImage(Integer recordId, MultipartFile[] files) throws IOException {
        String groupName = groupService.queryGroupNameByGroupId(SecurityUtils.getGroupId());
        // C#组的路径需要单独修改，不然不可见
        if(groupName.equals("C#组")){
            groupName="CSHARP组";
        }
        //目录结构  /img/groupName/年分/
        File targetDir = FileUtils.createGroupDir(WebAppConfig.ROOT_DIR_RECORD,groupName);
        String urlRoot = File.separator+"record"+File.separator + groupName + File.separator +
                Calendar.getInstance().get(Calendar.YEAR);
        //插入文件信息到数据库中
        List<TrainingRecordFile> fileList = new ArrayList<>();
        for (MultipartFile file : files) {
            if (file != null && !file.isEmpty()) {
                String fileName = FileUtils.createFileName(Objects.requireNonNull(file.getOriginalFilename()));
                File desFile = new File(targetDir, fileName);
                try {
                    file.transferTo(desFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                TrainingRecordFile fileInfo = new TrainingRecordFile();
                fileInfo.setFileUrl(urlRoot+File.separator+desFile.getName());
                fileInfo.setRecordId(recordId);
                fileInfo.setFileName(FileUtils.getFileName(file.getOriginalFilename()));
                fileInfo.setExtensionName(FileUtils.getExtensionName(file));
                //将文件信息添加到List中
                fileList.add(fileInfo);
            }
        }
        if (fileList.size()>0){
            String u = fileList.get(0).getFileUrl();
            u=u.substring(u.lastIndexOf('/')+1);
            ImageUtils.generateDirectoryThumbnail(WebAppConfig.ROOT+urlRoot,u);
        }
        return fileList;
    }


}
